#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define SOCKET_ERROR -1
#define BUF_SIZE 1024
void ErrorHandle(const std::string &msg)
{
  std::cout << "msg" << std::endl;
  exit(-1);
}
void Print(const std::string &msg)
{
  std::cout << msg << std::endl;
}
int main(int args, char *argv[])
{
#ifdef _WIN32
  SetConsoleOutputCP(65001); // 设置终端输出编码为UTF-8
#endif

  // step01:创建套接字
  int sock_clnt;
  sock_clnt = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

  // step02:请求连接服务端
  sockaddr_in addr_serv;
  memset(&addr_serv, 0, sizeof(addr_serv));
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(argv[1]);
  addr_serv.sin_port = htons(atoi(argv[2])); // 将char *str转为整数类型
  if ((connect(sock_clnt, (sockaddr *)&addr_serv, sizeof(addr_serv))) == SOCKET_ERROR)
    ErrorHandle("connect() error!");
  Print("connect() ok ...");

  // step03:传输数据
  std::cout << "操作数数量：";
  int len;
  char msg[BUF_SIZE] = "";
  std::cin >> len;
  char le = (char)(len + 48); // 将个位数的整数类型转为字符类型
  msg[0] = le;
  int num;
  for (int i = 0; i < len; ++i)
  {
    std::cout << "请输入第" << i + 1 << "个操作数：";
    scanf("%d", (int *)&msg[i * 4 + 1]); // 占四个bits
  }
  fgetc(stdin);
  std::cout << "请输入操作符：";
  char opt[1];
  scanf("%c", &msg[len * 4 + 1]);
  send(sock_clnt, msg, len * 4 + 2, 0);
  int result; // 存放服务端返回的结果
  recv(sock_clnt, (char *)&result, sizeof(result), 0);
  std::cout << "result:" << result << std::endl;
  close(sock_clnt);
  return 0;
}